<?php

namespace Modules\UI\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use Modules\User\Entities\User;
use ThrowException;
use Setting; 
use DB;

class Danmu extends Model
{
    protected $guarded = [];
    protected $table = 'danmus';
    static public $resourceName = '弹幕';

    protected $appends = ['node_type_text'];

    public function getNodeTypeTextAttribute()
    {
        $map = config('map.node_type_text');

        return @$map[$this->node_type] ?: 'unknow';
    }

    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }


    public function scopeStatus($query, $status) 
    {
        $now = now();
        
        if ($status === 'on_stock') {
            return $query->onStock();
        }
        elseif ($status === 'off_stock') {
            return $query->offStock();
        }
    }

    static public function beforeGetList($options)
    {
        if (@$options['status']) {
            $options['scopes']['status']  = $options['status'];
        }

        return $options;
    }

    // 
    static public function createWithPackage($package)
    {

        foreach ($package->skus as $sku) {
            self::createWith($sku);
        }
    }

    // 
    static public function createWith($packageSku)
    {
        $user = $packageSku->user;

        if (!$user) {
            return false;
        }

        return self::create([
            'user_id' => $user->id,
            'user_name' => $user->name,
            'user_headimg' => $user->headimg,
            'source_type' => 1,
            'node_type' => $packageSku->node_type,
            'node_id' => $packageSku->node_id,
            'node_uuid' => $packageSku->node_uuid,
            'node_title' => $packageSku->node_title,
            'sku_id' => $packageSku->sku_id,
            'sku_title' => $packageSku->title,
            'emited_at' => $packageSku->created_at,
            'is_special_sku' => $packageSku->is_special_sku ? 1 : 0,
        ]);
    }


}
